package com.linkafri.generate.code.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.linkafri.generate.code.bean.BaseBean;
import com.linkafri.generate.code.bean.Schema;
import com.linkafri.generate.code.bean.Table;
import com.linkafri.generate.code.service.BaseService;
import com.linkafri.generate.code.util.Utils;
import com.linkafri.generate.code.util.ZipCompress;
import com.linkafri.generate.commom.bean.Result;
import lombok.extern.slf4j.Slf4j;

/**
 * Created by Rocky on xxxx-xx-xx.
 */
@RequestMapping("/base")
@RestController
@Slf4j
@Scope("prototype")
public class BaseController {
    @Autowired
    BaseService baseService;
    @Value("${file.dir}")
    String fileDir;
    @Value("${file.zip}")
    String zipDir;
    @Value("${server.port}")
    String port;

    @PostMapping("/getAllSchema")
    public Result<List<Schema>> getAllSchema() throws Exception {
        Result<String> stringResult = new Result<>();
        stringResult.setValue("success");
        Result<List<Schema>> allSchema = baseService.getAllSchema();
        HashMap<String, String> result = new HashMap<>();
        return allSchema;
    }

    @PostMapping("/getAllTableNameBySchema")
    public Result<List<Table>> getAllTableBySchema(@RequestBody Schema schema) {

        Result<List<Table>> allTableBySchema = baseService.getAllTableNameBySchema(schema);

        return allTableBySchema;
    }

    @PostMapping("/getTableBySchemaAndTable")
    public Result<Table> getTableBySchemaAndTable(@RequestBody Map<String, String> map) {
        Table table = new Table();
        table.setName(map.get("tableName"));
        Schema schema1 = new Schema();
        schema1.setName(map.get("schemaName"));
        return baseService.getTableBySchemaAndTable(schema1, table, null);
    }

    @RequestMapping(value = "/testDownload", method = RequestMethod.GET)
    public void testDownload(HttpServletRequest request, HttpServletResponse res) {

        String fileName = request.getParameter("zipDir");
        res.setHeader("content-type", "application/octet-stream");
        res.setContentType("application/octet-stream");
        res.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            os = res.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(new File(zipDir + "/" + fileName)));
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("success");
    }


    @PostMapping("/testFTL")
    public Object testFTL(@RequestBody BaseBean baseBean, HttpServletResponse response) {
        String zipName = "";
        HashMap<String, String> res = new HashMap<>();
        try {
            InetAddress addr = InetAddress.getLocalHost();
            String ip = addr.getHostAddress().toString(); //获取本机ip
            File targetFileDel = new File(fileDir);
            if (targetFileDel.exists()) {
                Boolean b = Utils.deleteDirectory(targetFileDel.getPath());
                log.info("删除结果：" + b);
                File file = new File(fileDir);
                file.mkdir();
            }
            List<String> tableNameList = baseBean.getTableNameList();
            for (String table : tableNameList) {

                baseBean.setTableName(table);
                //处理逻辑删除字段
                List<HashMap<String, String>> delNames = baseBean.getDelNames();
                for (HashMap<String, String> delName : delNames) {
                    String tableName = delName.get("tableName");
                    if (tableName.equals(table)) {
                        String delNameStr = delName.get("delName");
                        baseBean.setCurrentIsDelete(delNameStr);
                        String classDelName = Utils.transferColumnToField(delNameStr);
                        baseBean.setCurrentIsDeleteClass(Utils.firstUpCase(classDelName));
                    }
                }
                Result<BaseBean> tableByBaseBean = baseService.getTableByBaseBean(baseBean);
                if (tableByBaseBean == null) {
                    res.put("success", "false");
                    res.put("msg", "delName not exit in " + table);
                    return res;
                }
            }
            ZipCompress zipCompress = new ZipCompress(zipDir, fileDir);
            zipName = "http://" + ip + ":" + port + "/base//testDownload/?zipDir=" + zipCompress.zip();
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info(zipName);

        res.put("url", zipName);
        return res;
    }

}
